package com.top.mall.main.access

import android.annotation.SuppressLint
import android.view.MotionEvent
import androidx.lifecycle.Observer
import com.module.lemlin.owner.OwnerViewModeFragment
import com.top.mall.R
import com.top.mall.jetpack.vm.AccessViewModel
import kotlinx.android.synthetic.main.fragment_access_check_code.*

class AccessCheckCodeFragment : OwnerViewModeFragment<AccessViewModel>() {

    companion object {

        private val ARRAY_CODE: Array<String?> = arrayOfNulls(6)

        fun newInstance(): AccessCheckCodeFragment {
            return AccessCheckCodeFragment()
        }
    }

    override val layoutResId: Int
        get() = R.layout.fragment_access_check_code

    override fun viewModel(): AccessViewModel {
        return createViewModel()
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun initView() {

        with(edit_check_code_content) {
            isLongClickable = false
            setTextIsSelectable(false)
            setOnClickListener {
                setSelection(text.length)
                isCursorVisible = false
            }
            setOnTouchListener { _, event ->
                if (event.action == MotionEvent.ACTION_UP) {
                    setSelection(text.length)
                    isCursorVisible = false
                }
                return@setOnTouchListener false
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        viewModel.clearLiveDataCheckCode()
    }

    override fun initViewMode() {
        viewModel.contentCheckCodeLiveData.observe(viewLifecycleOwner, Observer { code ->
            code?.let {
                fillDataCode(it)
            }
        })
        viewModel.isEnabledCheckCodeLiveData.observe(viewLifecycleOwner, Observer { isEnabled ->
            isEnabled?.let {
                text_check_code_confirm.isEnabled = it
            }
        })
    }

    override fun initData() {
        viewModel.observableCheckCode(edit_check_code_content)
    }

    /**
     * 设置验证码数据
     * */
    private fun fillDataCode(code: CharSequence) {
        val length: Int = code.length
        for (i: Int in (if (length == 0) 0 else length - 1)
                until ARRAY_CODE.size) {
            ARRAY_CODE[i] = null
        }
        for (i: Int in 0 until length) {
            ARRAY_CODE[i] = code.toList()[i].toString()
        }
        if (length != 0) {
            ARRAY_CODE[length - 1] = code.last().toString()
        }
        text_check_code_1.text = ARRAY_CODE[0]
        text_check_code_2.text = ARRAY_CODE[1]
        text_check_code_3.text = ARRAY_CODE[2]
        text_check_code_4.text = ARRAY_CODE[3]
        text_check_code_5.text = ARRAY_CODE[4]
        text_check_code_6.text = ARRAY_CODE[5]
    }

}